package com.example.androidmaze;

import java.util.List;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.GestureDetector.OnDoubleTapListener;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.support.v4.app.NavUtils;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.view.MotionEventCompat;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.os.Build;
import android.os.Build.VERSION;

public class PlayActivity extends Activity implements android.view.GestureDetector.OnGestureListener, OnDoubleTapListener{
	Maze maze;
	MazePanel mazeView;
	private static final String TAG = "PlayActivity";
	Singleton mazeInstance = Singleton.getInstance();
	private LinearLayout.LayoutParams params;
	String strOperation;
	final String manualOp = "Manual";
	private GestureDetectorCompat mDetector;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			strOperation = extras.getString("Operation");
		}
		
		Log.v(TAG, "Operation method: " + strOperation);
		if (strOperation.equals(manualOp)) {
		LinearLayout layout = new LinearLayout(this);
		LinearLayout buttonLayout = new LinearLayout(this);
		params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		layout.setLayoutParams(params);
		layout.setOrientation(LinearLayout.VERTICAL);
		params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		buttonLayout.setLayoutParams(params);
		buttonLayout.setOrientation(LinearLayout.HORIZONTAL);
		
		Button stepButton = new Button(this);
		stepButton.setLayoutParams(params);
		stepButton.setGravity(Gravity.CENTER);
		stepButton.setText("STEP");
		
		Button rotateLeftButton = new Button(this);
		rotateLeftButton.setLayoutParams(params);
		rotateLeftButton.setGravity(Gravity.CENTER);
		rotateLeftButton.setText("ROTATE LEFT");
		
		Button rotateRightButton = new Button(this);
		rotateRightButton.setLayoutParams(params);
		rotateRightButton.setGravity(Gravity.CENTER);
		rotateRightButton.setText("ROTATE RIGHT");
		
		//aligns buttons in center
		params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		buttonLayout.setLayoutParams(params);
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_play);
		
		//reads singleton generated maze
		this.maze = mazeInstance.getMaze();
		//creates new mazeView
		mazeView = new MazePanel(this);
		
		params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		mazeView.setLayoutParams(params);
		buttonLayout.addView(rotateLeftButton);
		buttonLayout.addView(stepButton);
		buttonLayout.addView(rotateRightButton);
		buttonLayout.setGravity(Gravity.CENTER);
		
//		layout.addView(stepButton);
//		layout.addView(rotateLeftButton);
//		layout.addView(rotateRightButton);
		layout.addView(buttonLayout);
		layout.addView(mazeView);
		
		addTouchListener();

		Log.v(TAG, "setting content view to layout view");
		setContentView(layout);

		//sets mazeView to maze object
		maze.setMazePanel(mazeView);
		
	
		Log.v(TAG, "notifying view redraw in maze object");
		maze.notifyViewerRedraw(); //must do this for maze to draw first
		
		// Show the Up button in the action bar.
		setupActionBar();
		
		
		stepButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Log.v(TAG, "Step Pressed");
				maze.keyDown('s');
				//toFinish(v);
			}
		});
		
		rotateLeftButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Log.v(TAG, "Rotate Left Pressed");
				maze.keyDown('l');
				
			}
		});
		
		rotateRightButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Log.v(TAG, "Rotate Right Pressed");
				maze.keyDown('r');
				
			}
		});
	}
	//Robots:
		else { 
			//create robot maze
			if (strOperation.equals("Gambler")) {
				//TODO
			}
			else if (strOperation.equals("CuriousGambler")) {
				//TODO
			}
			else if (strOperation.equals("Wizard")) {
				//TODO
			}
			else { //(strOperation.equals("WallFollower)) {
				//TODO
			}
		}
	}
	
	public void toFinish(View view) {
		Intent intent = new Intent(this, FinishActivity.class);
		startActivity(intent);
	}
	
	/**
	 * Set up the {@link android.app.ActionBar}, if the API is available.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	private void setupActionBar() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.play, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
	    	Intent intent = new Intent(this, TitleActivity.class);
	    	Log.v(TAG, "BACK button pressed");
			Log.v(TAG, "To activity TitleActivity");
			startActivity(intent);
	        return true;
	    }

	    return super.onKeyDown(keyCode, event);
	}	
// Replaced by lower code
//	@Override
//	public boolean onTouchEvent(MotionEvent event){ 
//	        
//	    int action = MotionEventCompat.getActionMasked(event);
//	        
//	    switch(action) {
//	        case (MotionEvent.ACTION_DOWN) :
//	            Log.d("onTouchEvent","Action was DOWN");
//	            return true;
//	        case (MotionEvent.ACTION_MOVE) :
//	            Log.d("onTouchEvent","Action was MOVE");
//	            return true;
//	        case (MotionEvent.ACTION_UP) :
//	            Log.d("onTouchEvent","Action was UP");
//	        	maze.keyDown('s');
//	            return true;
//	        case (MotionEvent.ACTION_CANCEL) :
//	            Log.d("onTouchEvent","Action was CANCEL");
//	            return true;
//	        case (MotionEvent.ACTION_OUTSIDE) :
//	            Log.d("onTouchEvent","Movement occurred outside bounds " +
//	                    "of current screen element");
//	            return true;      
//	        default : 
//	            return super.onTouchEvent(event);
//	    }      
//	}
	
	public void addTouchListener()
	{
		this.mDetector = new GestureDetectorCompat(this,this);
		this.mDetector.setOnDoubleTapListener(this);
	}


	@Override
	public boolean onTouchEvent(MotionEvent event){
		this.mDetector.onTouchEvent(event);
		return super.onTouchEvent(event);
	}
	
	@Override
	public boolean onDown(MotionEvent e) {
//		maze.keyDown('d');
		return true;
	}


	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		
		int SWIPE_THRESHOLD_VELOCITY = 120;
		try {
	          double xDir = e1.getX() - e2.getX();
	          double yDir = e1.getY() - e2.getY();

	          Log.d("Console","xVel = " + xDir);
	          Log.d("Console","yVel = " + yDir);

	        if ( xDir > SWIPE_THRESHOLD_VELOCITY) {
	            if( yDir > SWIPE_THRESHOLD_VELOCITY) {
	                //Up-Left swipe
	            	 maze.keyDown('l');
	            }
	            else  if ( yDir < -SWIPE_THRESHOLD_VELOCITY){
	                //Down-Left swipe
	            	 maze.keyDown('l');
	            }
	            else{
	                //Left swipe
	                maze.keyDown('l');
	            }

	            return true;
	        } else if (xDir < -SWIPE_THRESHOLD_VELOCITY) {

	            if( yDir > SWIPE_THRESHOLD_VELOCITY) {
	            	maze.keyDown('r');
	            	//Up-Right swipe
	            }
	            else  if ( yDir < -SWIPE_THRESHOLD_VELOCITY){
	            	maze.keyDown('r');
	            	//Down-Right swipe
	            }
	            else {
	                //Right swipe
	                maze.keyDown('r');
	            }

	            return true;

	        }

	        if ( yDir < -SWIPE_THRESHOLD_VELOCITY) {
	            //Down swipe
	        	maze.keyDown('d');
	            return true;
	        }


	        if ( yDir > SWIPE_THRESHOLD_VELOCITY) {
	            //Up swipe
	        	maze.keyDown('s');
	            return true;
	        }
	      } catch (Exception e) {
	        Log.e("YourActivity", "Error on gestures");
	      }

	      return false;
	}


	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}


	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public boolean onSingleTapUp(MotionEvent e) {
//		maze.keyDown('s');
		return false;
	}


	@Override
	public boolean onDoubleTap(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}


	@Override
	public boolean onDoubleTapEvent(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}


	@Override
	public boolean onSingleTapConfirmed(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}
	
}
